package com.ferryc.tcc.impl;

import com.ferryc.entity.Account;
import com.ferryc.entity.AccountDetail;
import com.ferryc.exception.HandleException;
import com.ferryc.exception.NSFException;
import com.ferryc.mapper.AccountDetailMapper;
import com.ferryc.mapper.AccountMapper;
import com.ferryc.tcc.IAccountTccService;
import com.ferryc.utils.DigitalUtils;
import com.netflix.discovery.converters.Auto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created by Ferry Chen on 2019/11/15.
 */
@Slf4j
@Service("accountServiceCancel")
public class AccountServiceCancel implements IAccountTccService {

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AccountDetailMapper accountDetailMapper;
    @Transactional
    @Override
    public void consume(String userId, double amount) {
        log.info("cancel..");
        Account qa = new Account();
        qa.setUserId(userId);
        List<Account> list = accountMapper.queryList(qa);
        if (!CollectionUtils.isEmpty(list)) {
            Account account = list.get(0);
            saveDetail("4", account.getId(), amount);
            account.setMoney(DigitalUtils.add(account.getMoney(), amount));
            account.setFrozen(DigitalUtils.subtract(account.getFrozen(), amount));
            account.setId(list.get(0).getId());
            int result = accountMapper.updateById(account);
            if (1 != result) {
                throw new HandleException();
            }
        }
    }

    private void saveDetail(String type, String accountId, double money) {
        AccountDetail detail = new AccountDetail();
        detail.setAccountId(accountId);
        detail.setMoney(money);
        detail.setType(type);
        accountDetailMapper.insert(detail);
    }
}
